package com.liangxy.news.util;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.liangxy.news.model.User;

/**
 * Utility class for managing shared preferences
 */
public class SharedPreferencesManager {
    
    private static final String PREF_NAME = "news_preferences";
    private static final String KEY_USER = "user";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";
    private static final String KEY_CURRENT_USER = "current_user";
    private static final String KEY_NEWS_CATEGORIES = "news_categories";
    private static final String DEFAULT_CATEGORIES = "top,guonei,guoji,yule,tiyu,junshi,keji,caijing,youxi";
    
    private final SharedPreferences sharedPreferences;
    private final Gson gson;
    
    /**
     * Constructor
     * @param context Context
     */
    public SharedPreferencesManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }
    
    /**
     * Save user to shared preferences
     * @param user User to save
     */
    public void saveUser(User user) {
        if (user == null) return;
        
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String userJson = gson.toJson(user);
        editor.putString(KEY_USER, userJson);
        editor.putBoolean(KEY_IS_LOGGED_IN, true);
        editor.putString(KEY_CURRENT_USER, user.getPhone());
        editor.apply();
    }
    
    /**
     * Get user from shared preferences
     * @return User object or null if not found
     */
    public User getUser() {
        String userJson = sharedPreferences.getString(KEY_USER, null);
        if (userJson != null) {
            try {
                return gson.fromJson(userJson, User.class);
            } catch (Exception e) {
                // 如果解析失败，清除用户数据
                clearUser();
                return null;
            }
        }
        return null;
    }
    
    /**
     * Get user ID from shared preferences
     * @return User ID or null if not logged in
     */
    public String getUserId() {
        User user = getUser();
        return user != null ? user.getId() : null;
    }
    
    /**
     * Check if user is logged in
     * @return True if logged in, false otherwise
     */
    public boolean isLoggedIn() {
        boolean isLoggedIn = sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
        // 确保用户对象也存在
        if (isLoggedIn && getUser() == null) {
            // 如果登录状态为true但用户对象为null，则重置登录状态
            setLoggedIn(false);
            return false;
        }
        return isLoggedIn;
    }
    
    /**
     * Set logged in status
     * @param isLoggedIn True if logged in, false otherwise
     */
    public void setLoggedIn(boolean isLoggedIn) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
        if (!isLoggedIn) {
            // 如果登出，清除用户数据
            editor.remove(KEY_USER);
            editor.remove(KEY_CURRENT_USER);
        }
        editor.apply();
    }
    
    /**
     * Set current user
     * @param phoneNumber User phone number
     */
    public void setCurrentUser(String phoneNumber) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_CURRENT_USER, phoneNumber);
        editor.apply();
    }
    
    /**
     * Get current user phone number
     * @return Current user phone number
     */
    public String getCurrentUser() {
        return sharedPreferences.getString(KEY_CURRENT_USER, null);
    }
    
    /**
     * Get current user ID from shared preferences
     * @return Current user ID
     */
    public String getCurrentUserId() {
        return getUserId();
    }
    
    /**
     * Clear user data from shared preferences
     */
    public void clearUser() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_USER);
        editor.remove(KEY_CURRENT_USER);
        editor.putBoolean(KEY_IS_LOGGED_IN, false);
        editor.apply();
    }
    
    /**
     * Get news categories
     * @return Comma-separated list of news categories
     */
    public String getNewsCategories() {
        return sharedPreferences.getString(KEY_NEWS_CATEGORIES, DEFAULT_CATEGORIES);
    }
    
    /**
     * Save news categories
     * @param categories Comma-separated list of news categories
     */
    public void saveNewsCategories(String categories) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_NEWS_CATEGORIES, categories);
        editor.apply();
    }
    
    /**
     * Get boolean value from shared preferences
     * @param key Key
     * @param defaultValue Default value
     * @return Boolean value
     */
    public boolean getBoolean(String key, boolean defaultValue) {
        return sharedPreferences.getBoolean(key, defaultValue);
    }
    
    /**
     * Save boolean value to shared preferences
     * @param key Key
     * @param value Value
     */
    public void saveBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }
} 